package org.openfans.web;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.openfans.domain.Facade;
import org.openfans.domain.Fans;
import org.openfans.domain.Group;
import org.openfans.util.ThreadFans;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

public class HandleController extends MultiActionController {
	private static final int JOIN_GROUP = 1;

	private static final int LEAVE_GROUP = 2;

	private Facade facade;

	public void setFacade(Facade facade) {
		this.facade = facade;
	}

	public ModelAndView joinGroup(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		return userGroup(request, JOIN_GROUP);
	}

	public ModelAndView leaveGroup(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		return userGroup(request, LEAVE_GROUP);
	}

	private ModelAndView userGroup(HttpServletRequest request, int type) {
		int groupId = Integer.parseInt(request.getParameter("id"));
		Group group = facade.getGroup(groupId);
		Fans fans = facade.getFans(ThreadFans.get().getFansId());
		Map<String, Object> map = new HashMap<String, Object>();
		String message = null;
		if (type == JOIN_GROUP) {
			group = facade.addFansToGroup(group, fans);
			message = "你加入了小组";
			map.put("inGroup", new Boolean(true));
		} else if (type == LEAVE_GROUP) {
			group = facade.removeFansFromGroup(group, fans);
			message = "你离开了小组";
			map.put("inGroup", new Boolean(false));
		}
		map.put("group", group);
		map.put("message", message);

		return new ModelAndView("public/viewGroup", map);
	}
	
	public ModelAndView refreshFeed(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String feedId=request.getParameter("id");
		
		return userGroup(request, LEAVE_GROUP);
	}

}
